<template>
  <div class="order-history">
    <h1>Order History</h1>

    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="Patient">
          <el-input v-model="filterForm.patientName" placeholder="Patient name" clearable />
        </el-form-item>
        <el-form-item label="Date Range">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="To"
            start-placeholder="Start date"
            end-placeholder="End date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="Type">
          <el-select v-model="filterForm.type" placeholder="Order type" clearable>
            <el-option label="All" value="" />
            <el-option label="Medication" value="medication" />
            <el-option label="Medical Check" value="check" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="applyFilter">Search</el-button>
          <el-button @click="resetFilter">Reset</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-tabs v-model="activeTab" class="order-tabs">
      <el-tab-pane label="All Orders" name="all">
        <el-table
          :data="filteredOrders"
          style="width: 100%"
          :default-sort="{ prop: 'date', order: 'descending' }"
        >
          <el-table-column prop="id" label="Order ID" width="100" sortable />
          <el-table-column prop="date" label="Date" width="120" sortable>
            <template #default="scope">
              {{ formatDate(scope.row.date) }}
            </template>
          </el-table-column>
          <el-table-column prop="patientName" label="Patient" width="150" sortable />
          <el-table-column prop="type" label="Type" width="120">
            <template #default="scope">
              <el-tag :type="getTypeTag(scope.row.type)">
                {{ formatType(scope.row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="Description" />
          <el-table-column prop="status" label="Status" width="120">
            <template #default="scope">
              <el-tag :type="getStatusTag(scope.row.status)">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="Operations" width="180">
            <template #default="scope">
              <el-button size="small" @click="viewOrderDetail(scope.row)">Details</el-button>
              <el-button 
                v-if="scope.row.status === 'Pending'" 
                size="small" 
                type="danger" 
                @click="cancelOrder(scope.row.id)"
              >
                Cancel
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredOrders.length"
          layout="total, sizes, prev, pager, next, jumper"
          class="pagination"
        />
      </el-tab-pane>

      <el-tab-pane label="Medications" name="medication">
        <el-table
          :data="medicationOrders"
          style="width: 100%"
          :default-sort="{ prop: 'date', order: 'descending' }"
        >
          <el-table-column prop="id" label="Order ID" width="100" sortable />
          <el-table-column prop="date" label="Date" width="120" sortable>
            <template #default="scope">
              {{ formatDate(scope.row.date) }}
            </template>
          </el-table-column>
          <el-table-column prop="patientName" label="Patient" width="150" sortable />
          <el-table-column prop="drugName" label="Medication" />
          <el-table-column prop="quantity" label="Quantity" width="100" />
          <el-table-column prop="status" label="Status" width="120">
            <template #default="scope">
              <el-tag :type="getStatusTag(scope.row.status)">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="Operations" width="180">
            <template #default="scope">
              <el-button size="small" @click="viewOrderDetail(scope.row)">Details</el-button>
              <el-button 
                v-if="scope.row.status === 'Pending'" 
                size="small" 
                type="danger" 
                @click="cancelOrder(scope.row.id)"
              >
                Cancel
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-model:current-page="medicationPage"
          v-model:page-size="medicationPageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="medicationOrders.length"
          layout="total, sizes, prev, pager, next, jumper"
          class="pagination"
        />
      </el-tab-pane>

      <el-tab-pane label="Medical Checks" name="check">
        <el-table
          :data="checkOrders"
          style="width: 100%"
          :default-sort="{ prop: 'date', order: 'descending' }"
        >
          <el-table-column prop="id" label="Order ID" width="100" sortable />
          <el-table-column prop="date" label="Date" width="120" sortable>
            <template #default="scope">
              {{ formatDate(scope.row.date) }}
            </template>
          </el-table-column>
          <el-table-column prop="patientName" label="Patient" width="150" sortable />
          <el-table-column prop="checkName" label="Medical Check" />
          <el-table-column prop="department" label="Department" width="150" />
          <el-table-column prop="status" label="Status" width="120">
            <template #default="scope">
              <el-tag :type="getStatusTag(scope.row.status)">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="Operations" width="180">
            <template #default="scope">
              <el-button size="small" @click="viewOrderDetail(scope.row)">Details</el-button>
              <el-button 
                v-if="scope.row.status === 'Pending'" 
                size="small" 
                type="danger" 
                @click="cancelOrder(scope.row.id)"
              >
                Cancel
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-model:current-page="checkPage"
          v-model:page-size="checkPageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="checkOrders.length"
          layout="total, sizes, prev, pager, next, jumper"
          class="pagination"
        />
      </el-tab-pane>
    </el-tabs>

    <!-- Order Detail Dialog -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="`Order Details - #${selectedOrder.id || ''}`"
      width="60%"
    >
      <div v-if="selectedOrder.id">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="Order ID">{{ selectedOrder.id }}</el-descriptions-item>
          <el-descriptions-item label="Date">{{ formatDate(selectedOrder.date) }}</el-descriptions-item>
          <el-descriptions-item label="Patient">{{ selectedOrder.patientName }}</el-descriptions-item>
          <el-descriptions-item label="Type">{{ formatType(selectedOrder.type) }}</el-descriptions-item>
          <el-descriptions-item label="Status">
            <el-tag :type="getStatusTag(selectedOrder.status)">{{ selectedOrder.status }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="Created By">{{ selectedOrder.doctorName }}</el-descriptions-item>
        </el-descriptions>

        <div v-if="selectedOrder.type === 'medication'" style="margin-top: 20px;">
          <h3>Medication Details</h3>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="Medication">{{ selectedOrder.drugName }}</el-descriptions-item>
            <el-descriptions-item label="Quantity">{{ selectedOrder.quantity }}</el-descriptions-item>
            <el-descriptions-item label="Usage">{{ selectedOrder.usage }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div v-if="selectedOrder.type === 'check'" style="margin-top: 20px;">
          <h3>Medical Check Details</h3>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="Medical Check">{{ selectedOrder.checkName }}</el-descriptions-item>
            <el-descriptions-item label="Department">{{ selectedOrder.department }}</el-descriptions-item>
            <el-descriptions-item label="Duration">{{ selectedOrder.duration }} minutes</el-descriptions-item>
            <el-descriptions-item label="Note">{{ selectedOrder.note || 'N/A' }}</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div v-if="selectedOrder.status === 'Completed' && selectedOrder.type === 'check'" style="margin-top: 20px;">
          <h3>Results</h3>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="Result Date">{{ formatDate(selectedOrder.resultDate) }}</el-descriptions-item>
            <el-descriptions-item label="Result">{{ selectedOrder.result }}</el-descriptions-item>
            <el-descriptions-item label="Comments">{{ selectedOrder.resultComment }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <div style="margin-top: 20px;">
          <h3>Related Treatment</h3>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="Diagnosis">{{ selectedOrder.diagnosis }}</el-descriptions-item>
            <el-descriptions-item label="Treatment">{{ selectedOrder.treatment }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useOrderStore } from '../../stores/orders'
import dayjs from 'dayjs'
import { ElMessageBox, ElMessage } from 'element-plus'

const orderStore = useOrderStore()

// Filter form
const filterForm = ref({
  patientName: '',
  dateRange: [],
  type: ''
})

// Pagination
const currentPage = ref(1)
const pageSize = ref(10)
const medicationPage = ref(1)
const medicationPageSize = ref(10)
const checkPage = ref(1)
const checkPageSize = ref(10)

// Tabs
const activeTab = ref('all')

// Dialog
const detailDialogVisible = ref(false)
const selectedOrder = ref({})

// Mock data for development
const orders = ref([
  {
    id: 'ORD001',
    date: '2025-04-10',
    patientName: 'John Doe',
    patientId: 'P001',
    type: 'medication',
    description: 'Amoxicillin 500mg - 20 tablets',
    status: 'Completed',
    doctorName: 'Dr. Smith',
    drugName: 'Amoxicillin 500mg',
    quantity: 20,
    usage: '1 tablet 3 times daily',
    diagnosis: 'Upper respiratory infection',
    treatment: 'Antibiotics and rest'
  },
  {
    id: 'ORD002',
    date: '2025-04-10',
    patientName: 'John Doe',
    patientId: 'P001',
    type: 'check',
    description: 'Complete Blood Count',
    status: 'Completed',
    doctorName: 'Dr. Smith',
    checkName: 'Complete Blood Count',
    department: 'Laboratory',
    duration: 15,
    note: 'Check infection markers',
    diagnosis: 'Upper respiratory infection',
    treatment: 'Antibiotics and rest',
    resultDate: '2025-04-11',
    result: 'Normal',
    resultComment: 'WBC slightly elevated, consistent with bacterial infection'
  },
  {
    id: 'ORD003',
    date: '2025-04-09',
    patientName: 'Jane Smith',
    patientId: 'P002',
    type: 'medication',
    description: 'Lisinopril 10mg - 30 tablets',
    status: 'Completed',
    doctorName: 'Dr. Johnson',
    drugName: 'Lisinopril 10mg',
    quantity: 30,
    usage: '1 tablet daily',
    diagnosis: 'Hypertension',
    treatment: 'Blood pressure medication and lifestyle changes'
  },
  {
    id: 'ORD004',
    date: '2025-04-08',
    patientName: 'Robert Johnson',
    patientId: 'P003',
    type: 'check',
    description: 'ECG',
    status: 'Pending',
    doctorName: 'Dr. Smith',
    checkName: 'ECG',
    department: 'Cardiology',
    duration: 30,
    note: 'Routine check',
    diagnosis: 'Chest pain, to rule out cardiac issues',
    treatment: 'Diagnostic tests'
  }
])

// Computed orders
const filteredOrders = computed(() => {
  return applyFilters(orders.value).slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
  )
})

const medicationOrders = computed(() => {
  return applyFilters(orders.value.filter(order => order.type === 'medication')).slice(
    (medicationPage.value - 1) * medicationPageSize.value,
    medicationPage.value * medicationPageSize.value
  )
})

const checkOrders = computed(() => {
  return applyFilters(orders.value.filter(order => order.type === 'check')).slice(
    (checkPage.value - 1) * checkPageSize.value,
    checkPage.value * checkPageSize.value
  )
})

// Watch for tab changes
watch(activeTab, () => {
  if (activeTab.value === 'all') {
    currentPage.value = 1
  } else if (activeTab.value === 'medication') {
    medicationPage.value = 1
  } else if (activeTab.value === 'check') {
    checkPage.value = 1
  }
})

onMounted(async () => {
  // In a real app, you would fetch orders from the API
  console.log('Order history component mounted')
})

function formatDate(dateString) {
  return dayjs(dateString).format('YYYY-MM-DD')
}

function formatType(type) {
  if (type === 'medication') return 'Medication'
  if (type === 'check') return 'Medical Check'
  return type
}

function getTypeTag(type) {
  if (type === 'medication') return 'success'
  if (type === 'check') return 'warning'
  return 'info'
}

function getStatusTag(status) {
  if (status === 'Completed') return 'success'
  if (status === 'Pending') return 'warning'
  if (status === 'Cancelled') return 'danger'
  return 'info'
}

function viewOrderDetail(order) {
  selectedOrder.value = order
  detailDialogVisible.value = true
}

function applyFilters(ordersToFilter) {
  let result = [...ordersToFilter]
  
  // Filter by patient name
  if (filterForm.value.patientName) {
    const name = filterForm.value.patientName.toLowerCase()
    result = result.filter(order => 
      order.patientName.toLowerCase().includes(name)
    )
  }
  
  // Filter by date range
  if (filterForm.value.dateRange && filterForm.value.dateRange.length === 2) {
    const startDate = filterForm.value.dateRange[0]
    const endDate = filterForm.value.dateRange[1]
    result = result.filter(order => 
      dayjs(order.date).isAfter(dayjs(startDate).subtract(1, 'day')) && 
      dayjs(order.date).isBefore(dayjs(endDate).add(1, 'day'))
    )
  }
  
  // Filter by type
  if (filterForm.value.type) {
    result = result.filter(order => order.type === filterForm.value.type)
  }
  
  return result
}

function applyFilter() {
  currentPage.value = 1
  medicationPage.value = 1
  checkPage.value = 1
}

function resetFilter() {
  filterForm.value = {
    patientName: '',
    dateRange: [],
    type: ''
  }
  applyFilter()
}

async function cancelOrder(orderId) {
  try {
    await ElMessageBox.confirm(
      'Are you sure you want to cancel this order?',
      'Warning',
      {
        confirmButtonText: 'Yes',
        cancelButtonText: 'No',
        type: 'warning'
      }
    )
    
    // In a real app, you would call the API to cancel the order
    const orderIndex = orders.value.findIndex(o => o.id === orderId)
    if (orderIndex !== -1) {
      orders.value[orderIndex].status = 'Cancelled'
      ElMessage.success('Order cancelled successfully')
    }
  } catch (error) {
    // User cancelled the operation
  }
}
</script>

<style scoped>
.order-history {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.order-tabs {
  margin-top: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 